package com.dji.sdk.self.internal.controller;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;

import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.PersistableBundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.contrarywind.listener.OnItemSelectedListener;
import com.contrarywind.view.WheelView;
import com.dji.mapkit.core.maps.DJIMap;
import com.dji.mapkit.core.models.DJILatLng;
import com.dji.sdk.self.R;
import com.dji.sdk.self.internal.model.UavCondition;
import com.dji.sdk.self.internal.services.SendService;
import com.dji.sdk.self.internal.utils.DialogUtils;
import com.dji.sdk.self.internal.utils.LoginUtils;
import com.dji.sdk.self.internal.utils.MapUtils;
import com.dji.sdk.self.internal.utils.ToastUtils;
import com.google.android.material.navigation.NavigationView;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import dji.common.error.DJIError;
import dji.common.error.DJISDKError;
import dji.common.realname.AppActivationState;
import dji.common.useraccount.UserAccountState;
import dji.common.util.CommonCallbacks;
import dji.keysdk.DJIKey;
import dji.log.DJILog;
import dji.sdk.base.BaseComponent;
import dji.sdk.base.BaseProduct;
import dji.sdk.products.Aircraft;
import dji.sdk.realname.AppActivationManager;
import dji.sdk.sdkmanager.DJISDKInitEvent;
import dji.sdk.sdkmanager.DJISDKManager;
import dji.sdk.sdkmanager.LiveStreamManager;
import dji.sdk.useraccount.UserAccountManager;
import dji.ux.widget.FPVWidget;
import dji.ux.widget.MapWidget;

public class AllActivity extends BaseActivity {
    private static final String TAG = AllActivity.class.getSimpleName();

    private ArrayList<LinearLayout> viewList = new ArrayList<>();

    private LinearLayout root,rootParent,uxParent,loginParent,centerParent,streamParent,personCenter,stream,mapParent;
    private LinearLayout allInfo,uavInfo;
    private RelativeLayout uxWindow;
    private FrameLayout frameLayout;
    private WheelView wheelView;
    //主地图界面
    private ImageView ivDown;
    private TextView tvUavName,tvUserRole,tvUrl;
    private DrawerLayout mDrawerLayout;
    private Toolbar mToolbar,personToolbar,streamToolbar;
    private NavigationView mNavigationView;
    private Button btnOpen,btnGetUrl;
    private TextView tvInstantCurrent;
    private MapWidget rootMapWidget;
    private AMap aMap;
    private AlertDialog finishDialog;
    private LoginUtils loginUtils;
    private boolean isLogin = false;
    private String name=null;
    private SharedPreferences sharedPreferences;
    private String serialNumber;
    private String url;
    private UavCondition condition;
    private List<LatLng> latLngs = new ArrayList<LatLng>();
    private Marker droneMarker = null;
    private Polyline polyline;
    private Handler mHandler;
    private Handler mHandlerUI;
    private HandlerThread mHandlerThread = new HandlerThread("AllActivity");
    private AtomicBoolean hasAppActivationListenerStarted = new AtomicBoolean(false);
    private static final int MSG_INFORM_ACTIVATION = 1;
    private static final int ACTIVATION_DALAY_TIME = 3000;
    private AppActivationState.AppActivationStateListener appActivationStateListener;


    //注册大疆sdk
    private AtomicBoolean isRegistrationInProgress = new AtomicBoolean(false);
    private BaseComponent.ComponentListener mDJIComponentListener = new BaseComponent.ComponentListener() {
        @Override
        public void onConnectivityChange(boolean isConnected) {
            Log.d(TAG, "onComponentConnectivityChanged: " + isConnected);
        }
    };
    private LiveStreamManager.OnLiveChangeListener listener;

    private SendService sendService;
    private Intent sendIntent;
    private boolean bindSendService = false;


    private ServiceConnection sendServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            SendService.MyBinder binder = (SendService.MyBinder) service;
            sendService = binder.getService();
            sendService.setCallback(new SendService.CallBack() {
                @Override
                public void onDataChanged(UavCondition uavCondition) {
                    Log.i(TAG,"SEND SERVICE ON DATA CHANGED");
                    condition = uavCondition;
                    double latitude = condition.getLatitude();
                    double longitude = condition.getLongitude();
                    if(!Double.isNaN(latitude)&&!Double.isNaN(longitude)&&latitude!=0&&longitude!=0){
                        updateDroneLocation(condition.getLatitude(),condition.getLongitude());
                    }
                    Log.i(TAG,condition.toString());
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG,"====================================================================");
            Log.i(TAG,"SERVICE DISCONNECTED "+name.toString());
        }
    };
    private Handler serviceHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 100){
                if(bindSendService == false){
                    bindService(sendIntent,sendServiceConnection,BIND_AUTO_CREATE);
                    bindSendService = true;
                }
                if(!DJISDKManager.getInstance().getLiveStreamManager().isStreaming()&&url!=null){
                    startLiveShow();
                }


            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all);
        uxParent = findViewById(R.id.ux_view_parent);
        rootParent = findViewById(R.id.root_parent);
        loginParent = findViewById(R.id.login_view);
        centerParent = findViewById(R.id.person_center_parent);
        streamParent = findViewById(R.id.live_stream_parent);
        root = findViewById(R.id.gaode_view);
        uxWindow = uxParent.findViewById(R.id.ux_view);
        personCenter = findViewById(R.id.person_center);
        stream = findViewById(R.id.live_stream);
        mapParent = uxWindow.findViewById(R.id.map_view_parent);
        wheelView = findViewById(R.id.wv);
        wheelView.setCyclic(false);

        final List<String> mOptionsItems = new ArrayList<>();
        mOptionsItems.add("9");
        mOptionsItems.add("8");
        mOptionsItems.add("7");
        mOptionsItems.add("6");
        mOptionsItems.add("5");
        mOptionsItems.add("4");
        final List<String> changeItems = new ArrayList<>();
        changeItems.add("9");

        for(int i = 1;i<mOptionsItems.size()-1;i++){
            changeItems.add("-");
        }
        changeItems.add("4");

        wheelView.setAdapter(new ArrayWheelAdapter(changeItems));
        wheelView.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                Toast.makeText(AllActivity.this, "" + mOptionsItems.get(index), Toast.LENGTH_SHORT).show();
            }
        });


        listener = new LiveStreamManager.OnLiveChangeListener() {
            @Override
            public void onStatusChanged(int i) {
                ToastUtils.setResultToToast("status changed : " + i);
            }
        };

        Log.i(TAG,"ROOT "+root);
        Log.i(TAG,"uxWindow "+uxWindow);
        Log.i(TAG,"initUXView");
        rootMapWidget = root.findViewById(R.id.gaode_mapview);
        rootMapWidget.initAMap(new MapWidget.OnMapReadyListener() {
            @Override
            public void onMapReady(@NonNull @NotNull DJIMap djiMap) {
                initMapSetting(djiMap);
                aMap = (AMap) djiMap.getMap();
                Log.i(TAG,"ROOT MAP");
            }
        });
        rootMapWidget.onCreate(savedInstanceState);
        loginUtils = new LoginUtils(this);
        initView();

    }

        private void updateDroneLocation(double latitude,double longitude){
        LatLng pos = new LatLng(latitude, longitude);
        latLngs.add(pos);
        //Create MarkerOptions object
        final MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(pos);
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.aircraft));

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (droneMarker != null) {
                    droneMarker.remove();
                }
                if (checkGpsCoordination(latitude, longitude)) {
                    droneMarker = aMap.addMarker(markerOptions);
                    polyline =aMap.addPolyline(new PolylineOptions().
                            addAll(latLngs).width(10).color(Color.argb(255, 1, 1, 1)));
                    cameraUpdate(latitude,longitude);
                }
            }
        });
    }
    public static boolean checkGpsCoordination(double latitude, double longitude) {
        return (latitude > -90 && latitude < 90 && longitude > -180 && longitude < 180) && (latitude != 0f && longitude != 0f);
    }
    private void cameraUpdate(double latitude,double longitude){
        LatLng pos = new LatLng(latitude, longitude);
        float zoomlevel = (float) 20.0;
        CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(pos, zoomlevel);
        aMap.moveCamera(cu);
    }

    private void initMapSetting(DJIMap djiMap) {
        AMap mAMap= (AMap) djiMap.getMap();
        // 可触发定位并显示当前位置
        mAMap.setMyLocationEnabled(true);
        // 实例化UiSettings类对象
        MapUtils mapUtils = new MapUtils(djiMap);
        // 实例化UiSettings类对象
        UiSettings uiSettings = mAMap.getUiSettings();
        mapUtils.setUiSettings(uiSettings);
        // 初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        mapUtils.getLocationStyle(myLocationStyle);
        mapUtils.initCamera();
        // 初始化定位
        AMapLocationClient locationClient = new AMapLocationClient(getApplicationContext());
        // 设置定位回调监听
        locationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        // 可在其中解析amapLocation获取相应内容。
                        if (aMapLocation.getLongitude() != 0 && aMapLocation.getLatitude() != 0) {
                            mAMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(aMapLocation.getLatitude(),aMapLocation.getLongitude()),16,45,0)));
//                            mAMap.stopAnimation();
                            locationClient.stopLocation();
                        }
                    } else {
                        // 定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:" + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        });
        mapUtils.initLocationOption(locationClient);
        // 启动定位
        locationClient.startLocation();
    }
    private void initView() {
        initViewList();
        initPersonCenterView();
        initGaodeView();
        initGetLiveView();
        setVisible(rootParent);
    }

    private void setVisible(LinearLayout parent){
        for(int i = 0;i<viewList.size(); i++){
            if(viewList.get(i)!=parent){
                viewList.get(i).setVisibility(View.GONE);
            }else {
                viewList.get(i).setVisibility(View.VISIBLE);
            }
        }
    }

    private void initViewList(){
        viewList.add(centerParent);
        viewList.add(rootParent);
        viewList.add(loginParent);
        viewList.add(streamParent);
        viewList.add(uxParent);
        isLogin();
        sendIntent = new Intent(AllActivity.this,SendService.class);
    }


    private void initGaodeView() {
        initMenu();
        tvUavName = root.findViewById(R.id.tv_uav_name);
        frameLayout = root.findViewById(R.id.frame_layout);
        allInfo = root.findViewById(R.id.uav_allinfo);
        uavInfo = root.findViewById(R.id.uav_info);
        ivDown = root.findViewById(R.id.draw_up);
        ivDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int isVisible = uavInfo.getVisibility();
                if(isVisible>0){
                    uavInfo.setVisibility(View.VISIBLE);
                    ivDown.setImageResource(R.drawable.ic_arrow_up_bold);
                }else {
                    uavInfo.setVisibility(View.GONE);
                    ivDown.setImageResource(R.drawable.ic_arrow_down);
                }
                ivDown.setFocusable(true);
                uavInfo.setFocusable(true);
            }
        });
        tvUavName.setText("Test");
        btnOpen = root.findViewById(R.id.btn_uxsdk);
        btnOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("All","onClick");
                setVisible(uxParent);
                frameLayout.removeView(rootMapWidget);
                frameLayout.removeView(allInfo);
                mapParent.addView(rootMapWidget);
                if(rootMapWidget!=null){
                    rootMapWidget.getMap().setOnMapClickListener(new DJIMap.OnMapClickListener() {
                        @Override
                        public void onMapClick(DJILatLng djiLatLng) {
                            uxParent.setVisibility(View.GONE);
                            rootParent.setVisibility(View.VISIBLE);
                            mapParent.removeView(rootMapWidget);
                            uxWindow.removeView(mapParent);
                            frameLayout.addView(rootMapWidget);
                            frameLayout.addView(allInfo);
                        }
                    });
                }

            }
        });
        if(isLogin){
            startSDKRegistration();
        }

    }
    //初始化侧滑菜单项
    private void initMenu() {
        mDrawerLayout = root.findViewById(R.id.drawer_layout);
        mToolbar = root.findViewById(R.id.gaode_toolbar);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,mDrawerLayout,mToolbar,R.string.drawer_layout,R.string.drawer_layout);
        mDrawerLayout.addDrawerListener(toggle);
        toggle.setDrawerIndicatorEnabled(true);
        toggle.syncState();

        mNavigationView = root.findViewById(R.id.navigation_view_left);
        View headerView = mNavigationView.getHeaderView(0);
        tvUserRole = headerView.findViewById(R.id.tv_user_role);
        if(isLogin == true){
            String name = loginUtils.isLogin();
            tvUserRole.setText(name);
        }

        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.facility_manager:
                        ToastUtils.showToast("facilityManager");
                        break;
                    case R.id.personal_center:
                        mDrawerLayout.closeDrawers();
                        initPersonView();
                        break;
                    case R.id.data_statics:
                        break;
                    case R.id.flight_plan:
                        break;
                    case R.id.offline_map:
                        mDrawerLayout.closeDrawers();
                       Intent intent = new Intent(AllActivity.this,com.amap.api.maps.offlinemap.OfflineMapActivity.class);
                       startActivity(intent);
                        break;
                    case R.id.setting_live_stream_url:
                        //打开获取推流地址界面
                        mDrawerLayout.closeDrawers();
                        setVisible(streamParent);
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
    }

    private void initGetLiveView() {
        tvUrl = stream.findViewById(R.id.url);
        btnGetUrl = stream.findViewById(R.id.btn_getUrl);
        streamToolbar = stream.findViewById(R.id.url_toolbar);
        sharedPreferences = getSharedPreferences("LiveStreamUrl",0);
        String tempUrl = sharedPreferences.getString("liveUrl",null);
        String number = sharedPreferences.getString("serialNumber",null);
        streamToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setVisible(rootParent);
            }
        });

        if(serialNumber!=null&&!TextUtils.isEmpty(serialNumber)&&number!=null&&!TextUtils.isEmpty(number)&&tempUrl!=null&&!TextUtils.isEmpty(tempUrl)){
            if(serialNumber.equals(number)){
                url = tempUrl;
                Log.i(TAG,url);
                tvUrl.setText(tempUrl);
            }
        }else if(serialNumber!=null&&!TextUtils.isEmpty(serialNumber)){
            loginUtils.getUrl(serialNumber);
            getStreamUrl();
            if(url!=null){
                tvUrl.setText(url);
                if(isLogin == true){
                    startLiveShow();
                }
            }
        }
        btnGetUrl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(TAG,"btnGetUrl");
                if(!TextUtils.isEmpty(url)){
                    ToastUtils.setResultToToast("已获取");
                }else if(serialNumber!=null&&!TextUtils.isEmpty(serialNumber)){
                    Log.i(TAG,"BTN ELSE IF");
                   loginUtils.getUrl(serialNumber);
                   getStreamUrl();
                    if(url!=null){
                        tvUrl.setText(url);
                        if(isLogin == true){
                            startLiveShow();
                        }
                    }
                }
            }
        });
        Log.i(TAG,"initGetLiveView setVisible");
    }
    private void getStreamUrl(){
        loginUtils.setCallback(new LoginUtils.Callback() {
            @Override
            public void onDataChange(String pushUrl) {
                url = pushUrl;
            }
        });
    }
    private void startLiveShow() {
        if (!isLiveStreamManagerOn()) {
            return;
        }
        if (DJISDKManager.getInstance().getLiveStreamManager().isStreaming()) {
            ToastUtils.setResultToToast("already started!");
            return;
        }

        new Thread() {
            @Override
            public void run() {
                DJISDKManager.getInstance().getLiveStreamManager().setLiveUrl(url);
                int result = DJISDKManager.getInstance().getLiveStreamManager().startStream();
                DJISDKManager.getInstance().getLiveStreamManager().setStartTime();
                ToastUtils.setResultToToast("startLive:" + result +
                        "\n isVideoStreamSpeedConfigurable:" + DJISDKManager.getInstance().getLiveStreamManager().isVideoStreamSpeedConfigurable() +
                        "\n isLiveAudioEnabled:" + DJISDKManager.getInstance().getLiveStreamManager().isLiveAudioEnabled());
                Log.i("UXSDKActivity","startLive:" + result +
                        "\n isVideoStreamSpeedConfigurable:" + DJISDKManager.getInstance().getLiveStreamManager().isVideoStreamSpeedConfigurable() +
                        "\n isLiveAudioEnabled:" + DJISDKManager.getInstance().getLiveStreamManager().isLiveAudioEnabled());
            }
        }.start();
    }
    private boolean isLiveStreamManagerOn() {
        if (DJISDKManager.getInstance().getLiveStreamManager() == null) {
            ToastUtils.setResultToToast("No live stream manager!");
            return false;
        }
        return true;
    }

    private void initPersonView() {
        Log.i(TAG,"initPersonView");
        if(isLogin==true){
            Log.i(TAG,"initPersonView initPersonCenterView");
            setVisible(centerParent);
        }else{
            Log.i(TAG,"initPersonView initLoginView");
            initLoginView();
        }
    }

    private void initPersonCenterView(){
        personToolbar = personCenter.findViewById(R.id.tb_person);
        Log.i(TAG,"personToolbar "+personToolbar);
        personToolbar.setNavigationIcon(R.drawable.offline_back);
        personToolbar.inflateMenu(R.menu.login_menu);
        personToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if(item.getItemId()==R.id.logout){
                    AlertDialog.Builder builder = new AlertDialog.Builder(AllActivity.this)
                            .setTitle("提示")
                            .setMessage("确定退出账号吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    loginUtils.logout();
                                    isLogin = false;
                                    setVisible(rootParent);
                                    tvUserRole.setText("未登录");
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    return;
                                }
                            })
                            .setCancelable(true);
                    AlertDialog alertDialog = builder.create();
                    alertDialog.show();

                }
                return true;
            }
        });
        personToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setVisible(rootParent);
            }
        });
    }
    private void initLoginView(){
      Intent intent = new Intent(AllActivity.this,LoginActivity.class);
      startActivityForResult(intent,100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 200){
            name = data.getStringExtra("username");
            isLogin = true;
            tvUserRole.setText(name);
            if(bindSendService == false){
                bindService(sendIntent,sendServiceConnection,BIND_AUTO_CREATE);
                bindSendService = true;
            }
        }
    }

    private boolean isLogin(){
        name = loginUtils.isLogin();
        if(name!=null){
            isLogin = true;

        }
        return isLogin;
    }

    private void startSDKRegistration() {
        if (isRegistrationInProgress.compareAndSet(false, true)) {
            AsyncTask.execute(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.setResultToToast(AllActivity.this.getString(R.string.sdk_registration_doing_message));
                    DJISDKManager.getInstance().registerApp(AllActivity.this.getApplicationContext(), new DJISDKManager.SDKManagerCallback() {
                        @Override
                        public void onRegister(DJIError djiError) {
                            if (djiError == DJISDKError.REGISTRATION_SUCCESS) {
                                DJILog.e("App registration", DJISDKError.REGISTRATION_SUCCESS.getDescription());
                                DJISDKManager.getInstance().startConnectionToProduct();
                                ToastUtils.setResultToToast(AllActivity.this.getString(R.string.sdk_registration_success_message));
                            } else {
                                ToastUtils.setResultToToast(AllActivity.this.getString(R.string.sdk_registration_message) + djiError.getDescription());
                            }
                            Log.v(TAG, djiError.getDescription());
                        }
                        @Override
                        public void onProductDisconnect() {
                            Log.d(TAG, "onProductDisconnect");
                            if(bindSendService){
                                unbindService(sendServiceConnection);
                            }
                        }
                        @Override
                        public void onProductConnect(BaseProduct baseProduct) {
                            Log.d(TAG, String.format("onProductConnect newProduct:%s", baseProduct));
                            if(baseProduct instanceof Aircraft){
                                Aircraft aircraft = (Aircraft) baseProduct;
                                aircraft.getFlightController().getSerialNumber(new CommonCallbacks.CompletionCallbackWith<String>() {
                                    @Override
                                    public void onSuccess(String s) {
                                        serialNumber = s;
                                    }

                                    @Override
                                    public void onFailure(DJIError djiError) {

                                    }
                                });
                                if(isLogin != false){
                                    Message message = new Message();
                                    message.what = 100;
                                    serviceHandler.sendMessage(message);
                                }else{
                                    Intent intent = new Intent(AllActivity.this,LoginActivity.class);
                                    startActivityForResult(intent,100);
                                }

                                tvUavName.setText(baseProduct.getModel().getDisplayName());

                            }
                        }

                        @Override
                        public void onProductChanged(BaseProduct baseProduct) {
                        }

                        @Override
                        public void onComponentChange(BaseProduct.ComponentKey componentKey,
                                                      BaseComponent oldComponent,
                                                      BaseComponent newComponent) {
                            if (newComponent != null) {
                                newComponent.setComponentListener(mDJIComponentListener);
                            }
                            Log.d(TAG,
                                    String.format("onComponentChange key:%s, oldComponent:%s, newComponent:%s",
                                            componentKey,
                                            oldComponent,
                                            newComponent));

                        }

                        @Override
                        public void onInitProcess(DJISDKInitEvent djisdkInitEvent, int i) {
                        }
                        @Override
                        public void onDatabaseDownloadProgress(long current, long total) {
                        }
                    });
                }
            });
        }
    }
    private void sendDelayMsg(int msg, long delayMillis) {
        if (mHandler == null){
            return;
        }

        if (!mHandler.hasMessages(msg)) {
            mHandler.sendEmptyMessageDelayed(msg, delayMillis);
        }
    }
    private void addAppActivationListenerIfNeeded() {
        if (AppActivationManager.getInstance().getAppActivationState() != AppActivationState.ACTIVATED) {
            sendDelayMsg(MSG_INFORM_ACTIVATION, ACTIVATION_DALAY_TIME);
            if (hasAppActivationListenerStarted.compareAndSet(false, true)) {
                appActivationStateListener = new AppActivationState.AppActivationStateListener() {

                    @Override
                    public void onUpdate(AppActivationState appActivationState) {
                        if (mHandler != null && mHandler.hasMessages(MSG_INFORM_ACTIVATION)) {
                            mHandler.removeMessages(MSG_INFORM_ACTIVATION);
                        }
                        if (appActivationState != AppActivationState.ACTIVATED) {
                            sendDelayMsg(MSG_INFORM_ACTIVATION, ACTIVATION_DALAY_TIME);
                        }
                    }
                };
                AppActivationManager.getInstance().addAppActivationStateListener(appActivationStateListener);
            }
        }
    }

    private void removeAppActivationListenerIfNeeded() {
        if (hasAppActivationListenerStarted.compareAndSet(true, false)) {
            AppActivationManager.getInstance().removeAppActivationStateListener(appActivationStateListener);
        }
    }

    private void loginToActivationIfNeeded() {
        if (AppActivationManager.getInstance().getAppActivationState() == AppActivationState.LOGIN_REQUIRED) {
            UserAccountManager.getInstance()
                    .logIntoDJIUserAccount(AllActivity.this,
                            new CommonCallbacks.CompletionCallbackWith<UserAccountState>() {
                                @Override
                                public void onSuccess(UserAccountState userAccountState) {
                                    ToastUtils.setResultToToast("Login Successed!");
                                }

                                @Override
                                public void onFailure(DJIError djiError) {
                                    ToastUtils.setResultToToast("Login Failed!");
                                }
                            });

        }
    }
    @Override
    public void onBackPressed() {
        if (rootParent.getVisibility()==View.VISIBLE){
            AlertDialog.Builder builder =  new AlertDialog.Builder(AllActivity.this).setTitle("提示").setMessage("是否退出APP?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ActivityController.finishAll();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        return;
                    }
                })
                .setCancelable(true);
            finishDialog = builder.create();
            finishDialog.show();
        }else if (uxParent.getVisibility() == View.VISIBLE){
            uxParent.setVisibility(View.GONE);
            rootParent.setVisibility(View.VISIBLE);
            mapParent.removeView(rootMapWidget);
            frameLayout.addView(rootMapWidget);
            frameLayout.addView(allInfo);
            setVisible(rootParent);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        rootMapWidget.onResume();
        if (isLogin==true){
            Log.i(TAG,"onResume");
            tvUserRole.setText(name);
        }else{
            tvUserRole.setText("未登录");
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        rootMapWidget.onDestroy();
        if(bindSendService){
            unbindService(sendServiceConnection);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        rootMapWidget.onSaveInstanceState(outState);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        rootMapWidget.onLowMemory();
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        addAppActivationListenerIfNeeded();
        mHandlerThread.start();
        mHandler = new Handler(mHandlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_INFORM_ACTIVATION:
                        loginToActivationIfNeeded();
                        break;
                }
            }
        };
        mHandlerUI = new Handler(Looper.getMainLooper());
    }
    @Override
    public void onDetachedFromWindow() {
        removeAppActivationListenerIfNeeded();
        mHandler.removeCallbacksAndMessages(null);
        mHandlerUI.removeCallbacksAndMessages(null);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            mHandlerThread.quitSafely();
        } else {
            mHandlerThread.quit();
        }
        mHandlerUI = null;
        mHandler = null;
        super.onDetachedFromWindow();
    }
}